#include "X6.h"
#include <iostream>
using std::cout;
using std::endl;


bool X6::parser(const char* buffer, int recv_len)
{
   return msgParser(buffer, recv_len);
}



bool X6::msgParser(const char* buffer, int length)
{
    if(buffer == nullptr | length < 0) return false;
    if(status < 0) return false;
    if(status >= keywords.size()-1) return false;
    int i = 0;
    while(i < length && status < keywords.size() - 1){
        if(status != POS_OF_1 && status != POS_OF_2 && status != POS_OF_3){ 
            if(buffer[i] == keywords[status]){
                ++status;
            }
            else{
            	cout << "string mismatch! input char '" << buffer[i] << "' expected char '"<< keywords[status] << "'" <<endl;
                status = -1;
                return false;
            }
            ++i;
        }else{
            string temp;
            if(status == POS_OF_1) temp = "request-resource";
            else if(status == POS_OF_2) temp = "content-length";
            else temp = "data";
            while(i < length && buffer[i] != '$'){
                dataSet[temp] += buffer[i];
                ++i;
            }
            if(i < length && buffer[i] == '$')
                status++;
        }
        /*if(status == keywords.size() - 1 && i < length){
            status = -1;
            cout << "冗余字节，keywords.size() = " << keywords.size() << " length = "<< length <<endl;
            cout << "data: " << dataSet["data"] <<endl;
            return false; // 协议处理完毕后发现冗余字节，则说明客户端信息有误
        }*/
    }
    if(status == keywords.size() - 1){
        is_complete = true;
    }
    return true;
}

bool X6::isComplete()
{
    return is_complete;
}

void X6::reset()
{
    status = 0;
    dataSet["request-resource"] = string();
    dataSet["content-length"] = string();
    dataSet["data"] = string();
    is_complete = false;
}